package com.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.File;
import java.util.UUID;

/**
 * Created by Administrator on 2020/2/19 0019.
 */
public class UploadImgUtil {
    private static String ACCESS_KEY =QiniuConfig.getAccessKey();
    private static String SECRET_KEY =QiniuConfig.getSecretKey();
    private static String bucketname = QiniuConfig.getBucket();
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);// 密钥配置
    private static Configuration cfg = new Configuration(Region.region0());
    //...其他参数参考类注释
    private static  UploadManager uploadManager = new UploadManager(cfg); // 创建上传对象

    private static String newName(String oldName){
        String[] datas = oldName.split("\\.");
        String type=datas[datas.length-1];
        String newName= UUID.randomUUID().toString().replace("-","")+'.'+type;
        return newName;
    }

    public static String getUpToken(){
        return auth.uploadToken(bucketname);
    }

    public static String upload(byte[] bytes,String fileName){
        String url =null;
        Response response=null;
        String imgName =null;
        String key=newName(fileName);
        try {
            response=uploadManager.put(bytes,key,getUpToken());
            imgName=(String) response.jsonToMap().get("key");
            url=QiniuConfig.getDomainOfBucket()+imgName;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return url;
    }
    public static String upload(File file, String fileName){
        String url = null;
        Response res = null;
        String imgName = null;
        try {
            res = uploadManager.put(file, newName(fileName), getUpToken());
            imgName = (String) res.jsonToMap().get("key");
            url = QiniuConfig.getDomainOfBucket()+imgName;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static void main(String[] args){
        File file=new File("D:/imgs/a.gif");
        String upload = upload(file, "a.gif");
//        BucketManager bucketMgr = new BucketManager(auth, "");
//        bucketMgr.delete()
        System.out.println(upload);
    }
}
